package com.dlc.shop.user.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.model.ShopCustomer;
import com.dlc.shop.bean.model.User;
import com.dlc.shop.bean.model.UserExtension;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.i18n.I18nMessage;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.security.api.util.SecurityUtils;
import com.dlc.shop.service.ShopCustomerService;
import com.dlc.shop.service.UserExtensionService;
import com.dlc.shop.service.UserService;
import com.dlc.shop.user.common.dto.LevelDetailDto;
import com.dlc.shop.user.common.dto.LevelDto;
import com.dlc.shop.user.common.model.UserLevelLang;
import com.dlc.shop.user.common.service.UserLevelCategoryService;
import com.dlc.shop.user.common.service.UserLevelCouponService;
import com.dlc.shop.user.common.service.UserLevelService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 会员等级
 *
 * @author LHD
 * @date 2019-12-19 10:27:46
 */
@RestController
@AllArgsConstructor
@RequestMapping("/p/score/scoreLevel" )
@Tag(name = "会员等级接口")
public class UserLevelController {

    private final UserLevelService levelService;
    private final UserService userService;
    private final UserExtensionService userExtensionService;
    private final ShopCustomerService shopCustomerService;
    private final UserLevelCouponService userLevelCouponService;
    private final UserLevelCategoryService userLevelCategoryService;

    /**
     *  0:根据用户的会员类型获取会员列表 2:获取全部会员列表
      */

    private static final Integer BY_LEVEL_TYPE = 0;
    private static final Integer ALL = 2;

    /**
     * 获取会员等级信息页信息
     */
    @GetMapping("/page" )
    @Operation(summary = "会员等级信息" , description = "会员等级信息")
    @Parameter(name = "levelType", description = "0:根据用户的会员类型获取会员列表 1:获取付费会员列表 2:获取全部会员列表" , required = true)
    public ServerResponseEntity<LevelDto> getScoreLogPage(Integer levelType) {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        UserExtension extension = userExtensionService.getOne(
                new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId, userId));
        if(Objects.equals(levelType, BY_LEVEL_TYPE)){
            levelType = extension.getLevelType() == null ? 0:extension.getLevelType();
        } else if (Objects.equals(levelType, ALL)){
            levelType = null;
        }
        List<LevelDetailDto> userLevels = levelService.selectLevelAndRights(levelType, Constant.PLATFORM_SHOP_ID);
        LevelDetailDto nowLevel = new LevelDetailDto();
        LevelDetailDto nextLevel = new LevelDetailDto();
        //通过用户积分获取当前等级和下一等级
        for (LevelDetailDto userLevel : userLevels) {
            if (extension.getLevel() >= userLevel.getLevel()) {
                nowLevel = userLevel;
                // 等级国际化
                levelLang(nowLevel);
            } else {
                nextLevel = userLevel;
                // 等级国际化
                levelLang(nextLevel);
                break;
            }
        }
        LevelDto userLevelDto = new LevelDto();
        userLevelDto.setNickName(user.getNickName());
        userLevelDto.setEndTime(user.getVipEndTime());
        userLevelDto.setScore(extension.getScore());
        userLevelDto.setGrowth(extension.getGrowth());
        userLevelDto.setNeedGrowth(nowLevel.getNeedGrowth());
        userLevelDto.setUserLevel(nowLevel);
        userLevelDto.setLevelType(nowLevel.getLevelType());
        userLevelDto.setLevelName(nowLevel.getLevelName());
        userLevelDto.setNextGrowth(nextLevel.getNeedGrowth() == null ?nextLevel.getNeedGrowth():nextLevel.getNeedGrowth());
        userLevelDto.setNextLevelName(nextLevel.getLevelName() == null ?nowLevel.getLevelName():nextLevel.getLevelName());
        userLevelDto.setUserLevels(userLevels);
        return ServerResponseEntity.success(userLevelDto);
    }

    /**
     * 处理等级国际化信息
     * @param levelDetailDto
     */
    private void levelLang(LevelDetailDto levelDetailDto){
        for (UserLevelLang userLevelLang : levelDetailDto.getUserLevelLangList()) {
            if (Objects.equals(userLevelLang.getLang(), I18nMessage.getLang())){
                levelDetailDto.setLevelName(userLevelLang.getLevelName());
                break;
            }
        }
    }

    /**
     * 返回金额最低的会员价格和年限
     */
    @GetMapping("/minAmountLevel" )
    @Operation(summary = "返回金额最低的会员价格和年限" , description = "返回金额最低的会员价格和年限")
    public ServerResponseEntity<LevelDetailDto> getScoreLogPage() {
        List<LevelDetailDto> userLevels = levelService.selectLevelAndRights(1, Constant.PLATFORM_SHOP_ID);
        //返回 先以金额升序 期数降序
        List<LevelDetailDto> levelDetailDtos = userLevels.stream().sorted(
                Comparator.comparing(LevelDetailDto::getNeedAmount).thenComparing(LevelDetailDto::getTermType, Comparator.reverseOrder())).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(levelDetailDtos)){
            return ServerResponseEntity.success();
        }
        return ServerResponseEntity.success(levelDetailDtos.get(0));
    }

    @GetMapping("/getShopLevelInfo" )
    @Operation(summary = "获取[店铺]会员等级信息", description =  "获取[店铺]会员等级信息")
    @Parameters({
            @Parameter(name = "shopId", description = "店铺Id", required = true),
            @Parameter(name = "levelType", description = "会员等级类型0为根据会员自身情况 1为付费 -1获取全部会员等级", required = true)
    })
    public ServerResponseEntity<LevelDto> getShopLevelInfo(Long shopId, Integer levelType) {
        String userId = SecurityUtils.getUser().getUserId();
        // 查询会员信息
        ShopCustomer shopCustomer = shopCustomerService.getOne(new LambdaQueryWrapper<ShopCustomer>()
                .eq(ShopCustomer::getShopId, shopId)
                .eq(ShopCustomer::getUserId, userId)
                .ne(ShopCustomer::getLevelType, -1));
        // 查询会员等级及其会员权益
        if (levelType == 0) {
            levelType = (shopCustomer == null || shopCustomer.getLevelType() == null) ? 0 : shopCustomer.getLevelType();
        } else if (levelType == 1){
            levelType = 1;
        } else {
            levelType = null;
        }
        List<LevelDetailDto> userLevels = levelService.selectLevelAndRights(levelType, shopId);
        // 构建LevelDto数据
        LevelDto userLevelDto = new LevelDto();
        User user = userService.getById(userId);
        userLevelDto.setNickName(user.getNickName());
        if (shopCustomer != null) {
            //获取当前等级和下一等级
            Map<Integer, LevelDetailDto> levelDetailDtoMap = userLevels.stream().filter(x -> Objects.equals(x.getLevelType(), shopCustomer.getLevelType())).collect(Collectors.toMap(LevelDetailDto::getLevel, ld -> ld));
            LevelDetailDto nowLevel = levelDetailDtoMap.get(shopCustomer.getLevel());
            LevelDetailDto nextLevel;
            if ((nextLevel = levelDetailDtoMap.get(shopCustomer.getLevel() + 1)) == null) {
                nextLevel = nowLevel;
            }
            userLevelDto.setEndTime(shopCustomer.getVipEndTime() == null ? null : shopCustomer.getVipEndTime());
            userLevelDto.setGrowth(shopCustomer.getGrowth());
            if (nowLevel != null) {
                userLevelDto.setNeedGrowth(nowLevel.getNeedGrowth());
                userLevelDto.setLevelType(nowLevel.getLevelType());
                userLevelDto.setLevelName(nowLevel.getLevelName());
                userLevelDto.setUserLevel(nowLevel);
            }
            if (nextLevel != null) {
                userLevelDto.setNextGrowth(nextLevel.getNeedGrowth());
                userLevelDto.setNextLevelName(nextLevel.getLevelName());
            }
            // 补充会员优惠券
            userLevelDto.setCoupons(userLevelCouponService.listCouponAndGetInfoByLevelId(shopCustomer.getLevelId(), shopCustomer.getUserId()));
            // 补充折扣商品
            userLevelDto.setDiscountProducts(userLevelCategoryService.listDiscountProdByLevel(20, shopCustomer.getLevelId(), shopCustomer.getShopId()));
        }
        userLevelDto.setUserLevels(userLevels);
        return ServerResponseEntity.success(userLevelDto);
    }

    @GetMapping("/listLevels" )
    @Operation(summary = "获取会员等级列表", description =  "获取会员等级列表")
    @Parameters({
            @Parameter(name = "shopId", description = "店铺Id(0则查询平台会员)", required = true),
    })
    public ServerResponseEntity<List<LevelDetailDto>> listLevels(Long shopId) {
        List<LevelDetailDto> userLevels = levelService.selectLevelAndRights(null, shopId);
        return ServerResponseEntity.success(userLevels);
    }
}
